#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QFileDialog>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    QString path = QFileDialog::getOpenFileName(this, "open", "../");
    if(path.isEmpty() == false) //文件非空
    {
        // 创建文件对象
        QFile file(path);
        #if 0 // 全读
        // 打开文件（只读）
        if(file.open(QIODevice::ReadOnly) == true)
        {
            // 读文件 默认识别utf8
            QByteArray file_data = file.readAll();
            // 显示到编辑区
            ui->textEdit->setText(QString(file_data));
        }
        #endif
        #if 1 // 一行一行读
        if(file.open(QIODevice::ReadOnly) == true)
        {
            QByteArray read_buf;
            while(file.atEnd() == false)
            {
                read_buf += file.readLine();

            }
            ui->textEdit->setText(QString(read_buf));
        }
        #endif
        // 关闭文件
//        file.close();
    }
    else
    {

    }
}

void Widget::on_pushButton_2_clicked()
{
    QString path = QFileDialog::getSaveFileName(this, "save", "../", "TXT(*.txt)");
    if(path.isEmpty() == false)
    {
        QFile file;
        file.setFileName(path);
        bool isok = file.open(QIODevice::WriteOnly);
        if(isok == true)
        {
            QString str = ui->textEdit->toPlainText();

//            file.write(str.toUtf8());
        }
        file.close();
    }
}
